<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="药品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入药品名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="批准文号" prop="authorizedNo">
        <el-input
          v-model="queryParams.authorizedNo"
          placeholder="请输入批准文号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['msfx:druginfo:import']"
        >新增
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"  border :data="drugInfoList">
      <el-table-column label="编号" align="center" prop="id" width="60"/>
      <el-table-column label="药品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
      <el-table-column label="批准文号" align="center" prop="authorizedNo" :show-overflow-tooltip="true"/>
      <el-table-column label="子类编码" align="center" prop="typeNo" width="130"/>
      <el-table-column label="制剂规格" align="center" prop="spec" :show-overflow-tooltip="true"/>
      <el-table-column label="包装规格" align="center" prop="packageSpec"  width="150"/>
      <el-table-column label="计量单位" align="center" prop="packUnit" width="100"/>
      <el-table-column label="包装层级" align="center" prop="codeLevel" width="100"/>
      <el-table-column label="包装比例" align="center" prop="pkgRatio" width="100"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入产品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" @close="reset" append-to-body>
      <el-form :model="fileForm" :rules="fileRules" ref="fileForm" label-width="100px" class="demo-ruleForm">
        <el-form-item prop="files">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xml"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="handleFileSuccess"
            :data="upload.formData"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading"
                       v-hasPermi="['msfx:druginfo:import']"
                       @click="submitUpload">导入药品信息
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传xml文件</div>
          </el-upload>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>

import {getToken} from '@/utils/auth';
import {listDrugInfo} from '@/api/msfx/druginfo';

export default {
  name: "msfxDrug",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true, // 确保 showSearch 被声明为响应式属性
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      token: '',
      // 药品信息
      drugInfoList: [], // 确保初始化为空数组
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/btrh/msfx/drugs",
        // 上传的文件列表
        fileList: [],
        formData: {
          factory: ""
        }
      },
      // 查询参数
      queryParams: { // 确保 queryParams 被声明为响应式属性
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        authorizedNo: undefined,
        status: undefined
      },
      // 表单参数
      fileForm: {
        factory: ''
      },
      // 表单校验
      fileRules: {
        // factory: [
        //   {validator: checkFactory, trigger: 'blur'}
        // ]
      }
    };
  },
  created() {
    this.getList();
    this.token = getToken()
  },
  methods: {
    /** 查询药品列表 */
    getList() {
      this.loading = true;
      listDrugInfo(this.queryParams).then(response => {
          if (response && response.rows) {
            this.drugInfoList = response.rows;
            this.total = response.total;
          } else {
            this.drugInfoList = []; // 确保即使无数据也为空数组
          }
          this.loading = false;
        }
      ).catch(() => {
        this.drugInfoList = []; // 捕获异常时也初始化为空数组
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.upload.fileList = [];
      this.fileForm = {}
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 文件改变处理 */
    handleChange(file, fileList) {
      this.upload.fileList = fileList;
    },

    /** 文件移除处理 */
    handleRemove(file, fileList) {
      this.upload.fileList = fileList;
    },

    // 文件提交处理
    submitUpload() {
      this.$refs["fileForm"].validate(valid => {
          if (valid) {
            if (this.upload.fileList.length > 0) {
              this.$refs.upload.submit();
            } else {
              this.$message({
                message: "请选择需要导入的药品信息文件",
                type: "warning"
              });
            }
          }
        }
      )
    },

// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.open = false;
      this.getList();
      if (response.code === 200) {
        this.$message({
          message: response.msg,
          type: 'success'
        });
      } else {
        this.$message({
          message: response.msg,
          type: 'error'
        });
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "导入药品信息";
    }
  }
}
</script>
